package com.neo.tiny.admin.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.neo.tiny.common.jackson.JavaTimeModule;
import com.neo.tiny.deserializer.SimpleGrantedAuthorityDeserializer;
import com.neo.tiny.config.BaseRedisConfig;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

/**
 * @Description:
 * @Author: yqz
 * @CreateDate: 2022/8/13 16:26
 */
@EnableCaching
@Configuration
public class RedisConfig extends BaseRedisConfig {

    @Bean
    @Override
    public RedisSerializer<Object> redisValueSerializer() {
        //创建JSON序列化器
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //必须设置，否则无法将JSON转化为对象，会转化成Map类型
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);

        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule()
                .addDeserializer(SimpleGrantedAuthority.class, new SimpleGrantedAuthorityDeserializer()));
        serializer.setObjectMapper(objectMapper);
        return serializer;
    }
}
